<template>
	<view class="container">
		<view class="search" :style="{ top: getStatusBarHeight() + 'px' }">
			<uni-search-bar @input="handleInput" v-model="searchValue" @confirm="confirm" focus @cancel="cancel"></uni-search-bar>
		</view>
		<view class="segmented-control">
			<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" styleType="text" activeColor="#007aff" />
			<view class="content" v-for="(item, index) in items" :key="index" v-show="current === index">
				<view class="result" v-if="searchValue.trim().length >= 2">
					<uv-skeletons v-if="loading" :loading="loading" :skeleton="skeleton"></uv-skeletons>
					<view v-else class="body">
						<view class="tab-title">为你找到了{{ searchNum }}条相关结果</view>
						<uni-card
							v-if="current === 0"
							@click="goToDetail(item.id)"
							class="card"
							style="margin-bottom: 20rpx"
							v-for="item in enterpriseList"
							:key="item.id"
							:title="item.name"
							isFull
							extra="额外信息"
						>
							<view class="msg">
								<view class="item">法定代表人：{{ item.legalRepresentative }}</view>
								|
								<view class="item">工商注册号：{{ item.registrationNo }}</view>
							</view>
							<view class="msg">
								<view class="item">注册资本：{{ item.registeredCapital }}</view>
								|
								<view class="item">经营状态： {{ item.operationStatus }}</view>
							</view>
							<view class="msg">
								<view class="item">注册地址：{{ item.registeredAddress }}</view>
							</view>
						</uni-card>
						<uni-card
							v-if="current === 1"
							class="card"
							style="margin-bottom: 20rpx"
							v-for="item in patentList"
							:key="item.id"
							@click="goToDetail(item.enterprise.id)"
							:title="item.name"
							isFull
							extra="公司信息"
						>
							<view class="tag-view">
								<uni-tag :text="item.patentType" type="primary" />
							</view>
							<view class="item">申请日：{{ formatDate(item.applicationDate) }}</view>
							<view class="item">注册日：{{ formatDate(item.registrationDate) }}</view>
							<view class="item">发明人: {{ item.applicant }}</view>
						</uni-card>
						<uni-card
							v-if="current === 2"
							class="card"
							style="margin-bottom: 20rpx"
							v-for="item in trademarkList"
							:key="item.id"
							@click="goToDetail(item.enterprise.id)"
							:title="item.name"
							isFull
							extra="公司信息"
						>
							<view class="date">申请日：{{ formatDate(item.applicationDate) }}</view>
							<view class="date">注册日：{{ formatDate(item.registrationDate) }}</view>
							<view class="applicant">发明人: {{ item.applicant }}</view>
						</uni-card>
						<uni-card
							v-if="current === 3"
							class="card"
							:thumbnail="`${BASE_URL}/${item.photo}`"
							style="margin-bottom: 20rpx"
							v-for="item in executiveList"
							:key="item.id"
							@click="goToDetail(item.enterprise.id)"
							:title="item.name"
							isFull
							extra="公司信息"
						>
							<view class="cause">职务：{{ item.position }}</view>
							<view class="date">学历：{{ item.education }}</view>
						</uni-card>
						<uni-load-more v-if="isButtom" :status="status" :content-text="contentText" />
						<view class="safe-area-insert-bottom"></view>
					</view>
				</view>
				<view class="history" v-else>
					<view class="title">
						<view class="history-title">历史搜索记录</view>
						<text v-if="historyList[current].length" @click="clearHistory(current)">清空</text>
					</view>
					<view v-if="historyList[current].length === 0">暂无记录</view>
					<view class="history-item">
						<view v-for="(his, idx) in historyList[current]" :key="`${current}-${idx}`" class="item">
							<text @click="goEnterprise(his)">{{ his }}</text>
							<uni-icons @click="deleteHistory(index, idx)" type="closeempty"></uni-icons>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { searchEnterprise, searchPatent, searchExecutive, searchTrademark } from '../../api/enterprise.js';
import { getStatusBarHeight } from '../../utils/system.js';
import debounce from 'lodash/debounce';
import { onReachBottom } from '@dcloudio/uni-app';
import { formatDate } from '../../utils/common.js';
import { onLoad } from '@dcloudio/uni-app';
import { BASE_URL } from '../../utils/system.js';

const loading = ref(true);
const searchValue = ref('');
const current = ref(0);
const items = ['公司', '专利', '商标', '高管'];
const status = ref('loading');
const isBuutom = ref(false);
const contentText = {
	contentdown: '查看更多',
	contentrefresh: '加载中',
	contentnomore: '没有更多'
};
const queryParams = reactive({
	pageNum: 1,
	pageSize: 10
});
const skeleton = ref([
	{
		type: 'line',
		num: 3,
		gap: '20rpx'
	}
]);
onReachBottom(() => {
	isBuutom.value = true;
	if (status.value === 'loading' || status.value === 'nomore') return;
	queryParams.pageNum++;

	if (current.value === 0) {
		getEnterpeiseList(searchValue.value);
	} else if (current.value === 1) {
		getPatentList(searchValue.value);
	} else if (current.value === 2) {
		getTrademarkList(searchValue.value);
	} else if (current.value === 3) {
		getExecutiveList(searchValue.value);
	}
});

const historyList = ref({
	0: [],
	1: [],
	2: [],
	3: []
});
const searchNum = ref(0);
const enterpriseList = ref([]);
const patentList = ref([]);
const trademarkList = ref([]);
const executiveList = ref([]);

const getEnterpeiseList = async (name = '') => {
	status.value = 'loading';
	try {
		const res = await searchEnterprise({ name, pageNo: queryParams.pageNum, pageSize: queryParams.pageSize });
		if (res.data.enterprises.length === 0) {
			status.value = 'nomore';
		} else {
			searchNum.value = res.data.totalCount;
			enterpriseList.value = [...enterpriseList.value, ...res.data.enterprises];
			status.value = 'more';
		}
	} catch (error) {
		status.value = 'nomore';
	}
};

const getPatentList = async (name = '') => {
	status.value = 'loading';
	try {
		const res = await searchPatent({ name, pageNo: queryParams.pageNum, pageSize: queryParams.pageSize });
		if (res.data.patents.length === 0) {
			status.value = 'nomore';
		} else {
			searchNum.value = res.data.totalCount;
			patentList.value = [...patentList.value, ...res.data.patents];
			status.value = 'more';
		}
	} catch (error) {
		status.value = 'nomore';
	}
};

const getTrademarkList = async (name = '') => {
	status.value = 'loading';
	try {
		const res = await searchTrademark({ name, pageNo: queryParams.pageNum, pageSize: queryParams.pageSize });
		if (res.data.trademark.length === 0) {
			status.value = 'nomore';
		} else {
			searchNum.value = res.data.totalCount;
			trademarkList.value = [...trademarkList.value, ...res.data.trademark];
			status.value = 'more';
		}
	} catch (error) {
		status.value = 'nomore';
	}
};

const getExecutiveList = async (name = '') => {
	status.value = 'loading';
	try {
		const res = await searchExecutive({ name, pageNo: queryParams.pageNum, pageSize: queryParams.pageSize });
		if (res.data.executive.length === 0) {
			status.value = 'nomore';
		} else {
			searchNum.value = res.data.totalCount;
			executiveList.value = [...executiveList.value, ...res.data.executive];
			status.value = 'more';
		}
	} catch (error) {
		status.value = 'nomore';
	}
};

const debouncedSearch = debounce(async (value) => {
	loading.value = true;
	queryParams.pageNum = 1;
	queryParams.pageSize = 10;
	searchNum.value = 0;
	if (current.value === 0) {
		// 公司
		enterpriseList.value = [];
		getEnterpeiseList(value);
	} else if (current.value === 1) {
		// 专利
		patentList.value = [];
		getPatentList(value);
	} else if (current.value === 2) {
		// 商标
		trademarkList.value = [];
		getTrademarkList(value);
	} else if (current.value === 3) {
		// 高管
		executiveList.value = [];
		getExecutiveList(value);
	}
	loading.value = false;
}, 1000);

const handleInput = (e) => {
	const value = e;
	searchValue.value = value;
	if (value.trim().length >= 2) {
		loading.value = true;
		debouncedSearch(value.trim());
	}
};
const loadHistory = () => {
	const storedHistory = uni.getStorageSync('searchHistory') || {};
	for (let i = 0; i < items.length; i++) {
		historyList.value[i] = storedHistory[i] || [];
	}
};

const saveHistory = () => {
	uni.setStorageSync('searchHistory', historyList.value);
};

const confirm = (e) => {
	const value = e.value?.trim() || searchValue.value.trim();
	if (!value || value.length < 2) {
		uni.showToast({
			title: '至少2两个关键字',
			icon: 'none'
		});
		return;
	}

	if (!historyList.value[current.value].includes(value)) {
		historyList.value[current.value].unshift(value);
	}

	saveHistory();
};

const goEnterprise = async (e) => {
	queryParams.pageNum = 1;
	queryParams.pageSize = 10;
	searchValue.value = e;
	searchNum.value = 0;

	if (current.value === 0) {
		getEnterpeiseList(searchValue.value);
	} else if (current.value === 1) {
		getPatentList(searchValue.value);
	} else if (current.value === 2) {
		getTrademarkList(searchValue.value);
	} else if (current.value === 3) {
		getExecutiveList(searchValue.value);
	}
};

const cancel = () => {
	uni.switchTab({
		url: '/pages/index/index'
	});
};

const onClickItem = (e) => {
	if (current.value !== e.currentIndex) {
		current.value = e.currentIndex;
		searchValue.value = '';
		enterpriseList.value = [];
		patentList.value = [];
		trademarkList.value = [];
		executiveList.value = [];
		loading.value = false;
	}
};

const deleteHistory = (tabIndex, itemIndex) => {
	historyList.value[tabIndex].splice(itemIndex, 1);
	saveHistory();
};

const clearHistory = (tabIndex) => {
	historyList.value[tabIndex] = [];
	saveHistory();
};

const goToDetail = (id) => {
	uni.navigateTo({
		url: `/pages/enterpriseDetail/enterpriseDetail?id=${id}`
	});
};

onLoad(() => {
	loadHistory();
});
</script>

<style lang="scss" scoped>
.container {
	.search {
		position: relative;
	}
	.segmented-control {
		margin-top: 60rpx;
		.content {
			margin-top: 5rpx;
			padding: 30rpx;
			border-top: 1px solid #ccc;
			.result {
				.tab-title {
					margin-bottom: 20rpx;
				}
				.card {
					position: relative;
					.tag-view {
						position: absolute;
						right: 20rpx;
					}
					.msg {
						display: flex;
						flex-wrap: wrap;
						.item {
							margin: 0 10rpx;
						}
					}
				}
			}
			.history {
				.title {
					display: flex;
					justify-content: space-between;
					.history-title {
						font-weight: bold;
						margin-bottom: 10px;
					}
				}
				.history-item {
					display: flex;
					justify-content: start;
					flex-wrap: wrap; // 启用自动换行
					margin-bottom: 5px;
					.item {
						background-color: #f2f2f2;
						border-radius: 10rpx;
						padding: 10rpx 15rpx;
						margin: 0 15rpx 15rpx 0;
						display: flex;
						justify-content: space-between;
						align-items: center;
						text {
							margin-right: 10rpx;
						}
					}
				}
			}
		}
	}
}
</style>
